package com.gitee.srurl.core.factory.id.oid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gitee.srurl.core.domain.OidStoreDomain;
import com.gitee.srurl.core.service.IOidStoreService;
import com.gitee.srurl.core.util.SpringContextUtil;
import com.gitee.srurl.oid.domain.OidStoreData;
import com.gitee.srurl.oid.store.IOidStore;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author zxw
 * @date 2023/5/9 21:20
 */
@Slf4j
public class OidMysqlStore implements IOidStore {

    private final IOidStoreService oidStoreService = SpringContextUtil.getBean(IOidStoreService.class);

    @Override
    public OidStoreData readCurrentData(long workerId) {

        LambdaQueryWrapper<OidStoreDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OidStoreDomain::getWorkerId, workerId);
        OidStoreDomain storeDomain = oidStoreService.getOne(queryWrapper);
        OidStoreData oidStoreData;
        if (storeDomain == null) {
            oidStoreData = OidStoreData.builder()
                    .storeSequence(0L)
                    .workerId(workerId)
                    .build();
        } else {
            Long sequence = Optional.ofNullable(storeDomain.getSequence()).orElse(0L);
            oidStoreData = OidStoreData.builder()
                    .storeSequence(sequence)
                    .workerId(workerId)
                    .build();
        }

        return oidStoreData;
    }

    @Override
    public void saveData(long workerId, OidStoreData oidStoreData) {

        Long sequence = oidStoreData.getStoreSequence();
        if (sequence == null) {
            log.error("写入文件序列号为空.");
            throw new NullPointerException("写入序列号为空！");
        }

        LambdaQueryWrapper<OidStoreDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OidStoreDomain::getWorkerId, workerId);
        OidStoreDomain storeDomain = oidStoreService.getOne(queryWrapper);
        if (storeDomain == null) {
            // 说明不存在
            LocalDateTime now = LocalDateTime.now();
            storeDomain = OidStoreDomain.builder()
                    .workerId(workerId)
                    .sequence(sequence)
                    .createTime(now)
                    .updateTime(now)
                    .build();
            oidStoreService.save(storeDomain);
        } else {
            // 说明存在 更新
            storeDomain.setSequence(sequence);
            storeDomain.setUpdateTime(LocalDateTime.now());
            oidStoreService.updateById(storeDomain);
        }
    }

    @Override
    public String type() {
        return "mysql";
    }
}
